const fs = require("fs");
const path = require("path");
const xlsx = require("node-xlsx");
const officegen = require("officegen");
const { pinyin } = require("pinyin-pro");
const { dialog } = require("@electron/remote");
const { ipcRenderer, shell } = require("electron");
const store = require("./store.js");

let processCount = 1;
let readDirerr;
const createOpenLink = (dir) => {
  let openLink = document.createElement("a");
  openLink.className = "open-link";
  openLink.innerText = "打开文件夹";
  document.querySelector(".progress-box").append(openLink);
  openLink.addEventListener("click", (e) => {
    e.preventDefault();
    shell.openPath(dir);
  });
};
const handlePinyin = (files) => {
  let { generateMode } = store.get("setting");

  if (files.length < 1) alert("请先选择文件");
  else {
    let fp = path.join(files[0].path);
    let xgIndex = fp.lastIndexOf("\\");
    let putPath = fp.slice(0, xgIndex);
    readDir()
      .then((result) => {
        if (!result.canceled) {
          let outPath = path.join(result.filePaths[0]);
          if (outPath == putPath) {
            alert("为避免原文本丢失，请勿和原文本使用相同目录");
          } else {
            processCount = 1;
            let span = document.querySelector(".progress-span");
            if (span !== null) span.remove();
            else {
              span = document.createElement("span");
              span.className = "progress-span";
              span.innerText = "正在运行中...";
            }
            document.querySelector(".progress-box").append(span);

            setTimeout(() => {
              generatePinyin(files, outPath, generateMode);
            }, 1000);
          }
        }
      })
      .catch((err) => {
        readDirerr = err;
        if (err.message.includes("resource busy or locked"))
          alert(
            "读取目录错误：请先关闭相同目录下的同名文件 " +
              path.basename(err.message)
          );
        else alert(`读取目录错误：${err.message}`);

        span = document.querySelector(".progress-span");
        if (span !== null) span.remove();
        else {
          span = document.createElement("span");
          span.className = "progress-span";
          span.innerText = "注音失败， 共" + processCount + "个文件";
        }
        document.querySelector(".progress-box").appendChild(span);
      });
  }
};

function generatePinyin(files, filePaths, generateMode) {
  let progress = document.querySelector(".progress");
  let buffer;
  let maxLine;
  let docx;
  let errFiles = [];
  switch (generateMode) {
    case "onlyTxt":
      files.forEach((file, index) => {
        // if (index < 1)
        //单章测试
        const txt = fs.readFileSync(file.path, "utf-8");
        if (!txt) {
          return console.log("文件读取失败,错误信息:", err);
        }
        //################## ---补丁1 去掉生成拼音后，章节数字旁边的多余空格，看着清爽
        // pinyinText = pinyinText.replaceAll(/　/g,'') //清除象形字间隔，Unicode值3000H
        // let arr1 = [...pinyinText.matchAll(/[0-9]\s+[0-9]/g)]
        // let arr2 = [...pinyinText.matchAll(/[0-9]\s+[a-z]/g)]
        // let arr3 = [...pinyinText.matchAll(/ +[0-9]/g)] //保留换行符

        // arr1.forEach((n, i) => pinyinText = pinyinText.replace(n[0], n[0].replace(/\s+/, '')))
        // arr2.forEach((n, i) => pinyinText = pinyinText.replace(n[0], n[0].replace(/\s+/, '')))
        // arr3.forEach((n, i) => pinyinText = pinyinText.replace(n[0], n[0].replace(/ +/, '')))

        // let arr4 = [...pinyinText.matchAll(/[0-9][a-z]/g)] //再打回一个空格
        // arr4.forEach((n, i) => {
        //   pinyinText = pinyinText.replace(n[0], n[0].substring(0,1) + ' ' + n[0].substring(1,2))
        // })
        // fs.writeFileSync(`./pinyinGithub/${file}`, pinyinText)
        // arr1 = []
        // arr2 = []
        // arr3 = []
        // arr4 = []
        // //################## ---补丁1

        // //################## ---补丁2 每小节首字母大写
        // let arr5 = [...pinyinText.matchAll(/^1 +[a-z]/g)]
        // let arr6 = [...pinyinText.matchAll(/\n[0-9]+ [a-z]/g)]
        // arr5.forEach((n, i) => pinyinText = pinyinText.replace(n[0], n[0].toUpperCase()))
        // arr6.forEach((n, i) => pinyinText = pinyinText.replace(n[0], n[0].toUpperCase()))
        // fs.writeFileSync(`./pinyinGithub/${file}`, pinyinText)
        // arr5 = []
        // arr6 = []
        //################## ---补丁2

        //################## ---补丁3 只对汉字做转换
        // [...txt.matchAll(/[\u4e00-\u9fa5]+/g)]

        //################## ---补丁3
        // let pinyinText = pinyin(txt1)
        // readDir()
        // fs.writeFile(path.join(filePaths[0], file.name), pinyinText, (err) => {
        //   if (err) {
        //     return console.log("生成失败：", err);
        //   }
        //   console.log("生成成功!");
        // });

        let pinyinText = getStringPinyin(txt);
        // 为了在所有写文件任务结束后，再触发提醒，改为同步执行
        const writeErr = fs.writeFileSync(
          filePaths + "\\" + file.name,
          pinyinText
        );
        if (writeErr) console.log("err", err);

        //每次生成完一个就反馈给主进程，同时反馈给页面
        let obj = {
          progress: processCount,
          // total: filec.length
          total: filec.length,
          errFiles,
        };
        ipcRenderer.send("setProgress", obj);
        // writeDOM(processCount, files.length);
        // timer = setInterval(_=>{
        // 	document.querySelector('.progress-span').innerText = "已完成" + current + "个文件"
        // 	let progress = document.querySelector('.progress');
        // 	progress.max = files.length;
        // 	progress.value = current;
        // 	progress.innerHTML = (current / files.length) * 100 + '%'
        // }, 100)
        if (processCount == files.length) {
          span = document.querySelector(".progress-span");
          if (span !== null) {
            span.remove();
            span = document.createElement("span");
            span.className = "progress-span";
            span.innerText = "注音完毕，共注音" + processCount + "个文件";
          } else {
            span.innerText = "注音完毕，共注音" + processCount + "个文件";
          }
          document.querySelector(".progress-box").append(span);
          createOpenLink(filePaths);
        }
        processCount++;
      });
      break;
    case "ChineseTxt":
      files.forEach((file, index) => {
        const txt = fs.readFileSync(file.path, "utf-8");
        // let txtCha = ''
        // let breakLoList = [...txt.matchAll(/\n/g)] //不能取数字了，获知正文中也会出现数字，重新改一下，用换行符试试
        // 单纯的中拼双行
        // breakLoList.forEach((loc, i) => {
        //     if (i == 0) txtCha += `\n${mPinyin(txt.substring(0, loc.index))}\n${txt.substring(0, loc.index)}`
        //     else if (i !== breakLoList.length - 1) {
        //         txtCha += `\n${mPinyin(txt.substring(loc.index, breakLoList[i + 1].index - 1))}\n${txt.substring(loc.index, breakLoList[i + 1].index)}`
        //     } else {
        //         txtCha += `\n${mPinyin(txt.substring(loc.index - 1))}\n${txt.substring(loc.index)}`
        //     }
        // })
        // fs.writeFile(`./${file}`, txtCha, (err) => {
        //     if (err) console.log("##创建失败## —— ", err);
        //     console.log("创建成功＜（＾－＾）＞");
        // });

        //只对汉字做转换
        function mPinyin(txt) {
          let arr7 = txt.split("");
          let arr8 = [...txt.matchAll(/[\u4e00-\u9fff]+/g)];
          let pinyinText = "";
          arr8.forEach((item, i) => {
            if (i == 0) {
              pinyinText += arr7.slice(0, item.index).join("");
            } else {
              pinyinText += arr7
                .slice(arr8[i - 1].index + arr8[i - 1][0].length, item.index)
                .join("");
            }
            pinyinText += pinyin(item[0]);
            // else pinyinText += c
          });
          // console.log(arr8)

          if (arr8.at(-1))
            pinyinText += arr7
              .slice(arr8.at(-1).index + arr8.at(-1)[0].length)
              .join("");
          return pinyinText;
        }

        // 1.先拿整段注音，以获得准确的拼音
        let arr7 = txt.split("");
        let arr10 = [...txt.matchAll(/[0-9]+/g)];
        let arr8 = [...txt.matchAll(/[\u4e00-\u9fa5]+/g)];
        let arr9 = []; //映射原文
        let pinyinText = "";
        arr8.forEach((item, i) => {
          if (i == 0) {
            arr9 = arr9.concat(arr7.slice(0, item.index));
          } else {
            arr9 = arr9.concat(
              arr7.slice(arr8[i - 1].index + arr8[i - 1][0].length, item.index)
            );
          }
          arr9 = arr9.concat(
            replaceUnicode(pinyin(item[0], { type: "array" }))
          );
        });
        if (arr8.length > 0)
          arr9 = arr9.concat(
            arr7.slice(arr8.at(-1).index + arr8.at(-1)[0].length)
          );

        const simpleVowelsDict = [
          "ā",
          "á",
          "ǎ",
          "à",
          "ō",
          "ó",
          "ǒ",
          "ò",
          "ē",
          "é",
          "ě",
          "è",
          "ī",
          "í",
          "ǐ",
          "ì",
          "ū",
          "ú",
          "ǔ",
          "ù",
          "ǖ",
          "ǘ",
          "ǚ",
          "ǜ",
          "ü",
          "ɑ",
          "ń",
          "ň",
        ];

        let length = 0; //记录每次换行前的拼音行的数组长度
        arr9.forEach((pinyinItem, pinyinIndex) => {
          if (pinyinItem == "\n") {
            let gap = 0;
            arr7
              .slice(pinyinIndex - length, pinyinIndex)
              .forEach((item, index) => {
                let char = arr7[pinyinIndex - length + index];
                let pin = arr9[pinyinIndex - length + index];
                if (gap % 7 == 0 && !/[0-9]|，|。|”|）|\n|\r/.test(char)) {
                  pinyinText += item.padEnd(pin.length) + " ";
                } else pinyinText += item.padEnd(pin.length);
                if (/[\u4e00-\u9fff]+/g.test(char)) {
                  gap += 1;
                }
              });
            length = 0;
          } else {
            if(pinyinItem == undefined) console.log("arr9",  arr9, pinyinIndex, index, file.name)
            if (
              pinyinItem
                .split("")
                .findIndex((item) => simpleVowelsDict.includes(item)) !== -1 ||
              /[a-zA-Z]/.test(pinyinItem)
            ) {
              pinyinText += pinyinItem + " ";
            } else {
              pinyinText += pinyinItem;
            }
            length++;
          }
        });

        const writeErr = fs.writeFileSync(
          filePaths + "\\" + file.name,
          pinyinText
        );
        if (writeErr) console.log("err", err);

        //每次生成完一个就反馈给主进程，同时反馈给页面
        let obj = {
          progress: processCount,
          // total: filec.length
          total: filec.length,
          errFiles,
        };
        ipcRenderer.send("setProgress", obj);
        // writeDOM(processCount, files.length);
        (obj.progress / files.length) * 200 + "px";

        // timer = setInterval(_=>{
        // 	document.querySelector('.progress-span').innerText = "已完成" + current + "个文件"
        // 	let progress = document.querySelector('.progress');
        // 	progress.max = files.length;
        // 	progress.value = current;
        // 	progress.innerHTML = (current / files.length) * 100 + '%'
        // }, 100)
        if (processCount == files.length) {
          span = document.querySelector(".progress-span");
          if (span !== null) {
            span.remove();
            span = document.createElement("span");
            span.className = "progress-span";
            span.innerText = "注音完毕，共注音" + processCount + "个文件";
          } else {
            span.innerText = "注音完毕，共注音" + processCount + "个文件";
          }
          document.querySelector(".progress-box").append(span);
          createOpenLink(filePaths);
        }
        processCount++;
      });
      break;
    case "ChineseExcelSingle":
      maxLine = 0;
      let tables = [];
      files.forEach((file, index) => {
        const txt = fs.readFileSync(file.path, "utf-8");
        tables.push({
          name: file.name,
          data: [],
        });
        //逐字对照
        let arr7 = txt.split("");
        let arr8 = [...txt.matchAll(/[\u4e00-\u9fa5]+/g)];
        let arr9 = []; //和原文长度相同的拼音数组
        let arr10 = [...txt.matchAll(/[0-9]+/g)];
        let arr11 = [];

        //基于数字单元在文本中的位置生成新的文本数组，将数字合并
        arr10.forEach((it, i) => {
          if (i == 0) frontIndex = 0;
          else frontIndex = arr10[i - 1]["index"] + arr10[i - 1][0].length;
          let frag = arr7.slice(frontIndex, it["index"]);
          arr11 = arr11.concat([...frag, it[0]]);
          //末尾的一段
          if (i == arr10.length - 1) {
            arr11 = arr11.concat(
              arr7.slice(arr10.at(-1).index + arr10.at(-1)[0].length)
            );
          }
        });

        //基于新的文本数组arr11映射拼音数组（长度相同，下标对应）
        // arr8.forEach((item, i) => {
        // 	if (i == 0) {
        // 		arr12 = arr12.concat(arr11.slice(0, item.index))
        // 	} else {
        // 		arr12 = arr12.concat(arr11
        // 			.slice(arr8[i - 1].index + arr8[i - 1][0].length, item.index))
        // 	}
        // 	arr12 = arr12.concat(replaceUnicode(pinyin(item[0], { type: 'array' })));
        // });
        // if (arr8.length > 0)
        // 	arr12 = arr12.concat(arr11
        // 		.slice(arr8.at(-1).index + arr8.at(-1)[0].length)
        // 	)
        // 	console.log(arr11, arr12)

        //采用上面的预处理，将所有的相邻数字合并为一个数组元素
        arr8.forEach((item, i) => {
          if (i == 0) {
            arr9 = arr9.concat(arr7.slice(0, item.index));
          } else {
            arr9 = arr9.concat(
              arr7.slice(arr8[i - 1].index + arr8[i - 1][0].length, item.index)
            );
          }
          arr9 = arr9.concat(
            replaceUnicode(pinyin(item[0], { type: "array" }))
          );
        });
        if (arr8.length > 0)
          arr9 = arr9.concat(
            arr7.slice(arr8.at(-1).index + arr8.at(-1)[0].length)
          );

        let length = 0; //记录每次换行前的拼音行的数组长度
        let pinRow = [];
        let charRow = [];
        arr9.forEach((pinyinItem, pinyinIndex) => {
          if (pinyinItem == "\n") {
            arr7
              .slice(pinyinIndex - length, pinyinIndex)
              .forEach((charItem, charIndex) => {
                charRow.push(charItem);
              });
            tables[index].data.push(pinRow);
            tables[index].data.push(charRow);
            if (maxLine < pinRow.length) maxLine = pinRow.length;
            pinRow = [];
            charRow = [];
            length = 0;
          } else {
            pinRow.push(pinyinItem);
            length++;
          }
        });
        //每次生成完一个就反馈给主进程，同时反馈给页面
        let obj = {
          progress: processCount,
          total: filec.length,
          errFiles,
        };
        ipcRenderer.send("setProgress", obj);
        (obj.progress / files.length) * 200 + "px";

        tables[index].options = {
          "!cols": new Array(maxLine).fill({ wch: 3 }),
        };
        if (processCount == files.length) {
          span = document.querySelector(".progress-span");
          if (span !== null) {
            span.remove();
            span = document.createElement("span");
            span.className = "progress-span";
            span.innerText = "注音完毕，共注音" + processCount + "个文件";
          } else {
            span.innerText = "注音完毕，共注音" + processCount + "个文件";
          }
          document.querySelector(".progress-box").append(span);
          createOpenLink(filePaths);
        }
        processCount++;
      });
      buffer = xlsx.build(tables);
      fs.writeFileSync(filePaths + "\\" + "注音结果.xlsx", buffer, (err) => {
        if (err) alert("失败：" + err.message);
        else buffer = null;
      });
      break;
    case "ChineseExcelMany":
      maxLine = 0;
      files.forEach((file, index) => {
        const txt = fs.readFileSync(file.path, "utf-8");
        let table = [{ name: "sheet", data: [] }];
        //逐字对照
        let arr7 = txt.split("");
        let arr8 = [...txt.matchAll(/[\u4e00-\u9fa5]+/g)];
        let arr9 = []; //和原文长度相同的拼音数组
        let arr10 = [...txt.matchAll(/[0-9]+/g)];
        let arr11 = [];

        //基于数字单元在文本中的位置生成新的文本数组，将数字合并
        arr10.forEach((it, i) => {
          if (i == 0) frontIndex = 0;
          else frontIndex = arr10[i - 1]["index"] + arr10[i - 1][0].length;
          let frag = arr7.slice(frontIndex, it["index"]);
          arr11 = arr11.concat([...frag, it[0]]);
          //末尾的一段
          if (i == arr10.length - 1) {
            arr11 = arr11.concat(
              arr7.slice(arr10.at(-1).index + arr10.at(-1)[0].length)
            );
          }
        });

        //基于新的文本数组arr11映射拼音数组（长度相同，下标对应）
        // arr8.forEach((item, i) => {
        // 	if (i == 0) {
        // 		arr12 = arr12.concat(arr11.slice(0, item.index))
        // 	} else {
        // 		arr12 = arr12.concat(arr11
        // 			.slice(arr8[i - 1].index + arr8[i - 1][0].length, item.index))
        // 	}
        // 	arr12 = arr12.concat(replaceUnicode(pinyin(item[0], { type: 'array' })));
        // });
        // if (arr8.length > 0)
        // 	arr12 = arr12.concat(arr11
        // 		.slice(arr8.at(-1).index + arr8.at(-1)[0].length)
        // 	)
        // 	console.log(arr11, arr12)

        //采用上面的预处理，将所有的相邻数字合并为一个数组元素
        arr8.forEach((item, i) => {
          if (i == 0) {
            arr9 = arr9.concat(arr7.slice(0, item.index));
          } else {
            arr9 = arr9.concat(
              arr7.slice(arr8[i - 1].index + arr8[i - 1][0].length, item.index)
            );
          }
          arr9 = arr9.concat(
            replaceUnicode(pinyin(item[0], { type: "array" }))
          );
        });
        if (arr8.length > 0)
          arr9 = arr9.concat(
            arr7.slice(arr8.at(-1).index + arr8.at(-1)[0].length)
          );

        let length = 0; //记录每次换行前的拼音行的数组长度
        let pinRow = [];
        let charRow = [];
        arr9.forEach((pinyinItem, pinyinIndex) => {
          if (pinyinItem == "\n") {
            arr7
              .slice(pinyinIndex - length, pinyinIndex)
              .forEach((charItem, charIndex) => {
                charRow.push(charItem);
              });
            table[0].data.push(pinRow);
            table[0].data.push(charRow);
            if (maxLine < pinRow.length) maxLine = pinRow.length;
            pinRow = [];
            charRow = [];
            length = 0;
          } else {
            pinRow.push(pinyinItem);
            length++;
          }
        });
        //每次生成完一个就反馈给主进程，同时反馈给页面
        let obj = {
          progress: processCount,
          total: filec.length,
          errFiles,
        };
        ipcRenderer.send("setProgress", obj);
        (obj.progress / files.length) * 200 + "px";

        table[0].options = {
          "!cols": new Array(maxLine).fill({ wch: 3 }),
        };
        if (processCount == files.length) {
          span = document.querySelector(".progress-span");
          if (span !== null) {
            span.remove();
            span = document.createElement("span");
            span.className = "progress-span";
            span.innerText = "注音完毕，共注音" + processCount + "个文件";
          } else {
            span.innerText = "注音完毕，共注音" + processCount + "个文件";
          }
          document.querySelector(".progress-box").append(span);
          createOpenLink(filePaths);
        }
        buffer = xlsx.build(table);
        const writeErr = fs.writeFileSync(
          filePaths +
            "\\" +
            file.name.replace(path.extname(file.name), "") +
            ".xlsx",
          buffer
        );
        if (writeErr) alert("失败：" + writeErr.message);
        processCount++;
      });
      break;
    case "ChineseWordIgnorePolyphonicPinyin":
      files.forEach((file, index) => {
        docx = null;
        docx = officegen("docx");
        let pObj = docx.createP();
        const txt = fs.readFileSync(file.path, "utf-8");
        // 1.先拿整段注音，以获得准确的拼音
        let arr7 = txt.split("");
        let arr10 = [...txt.matchAll(/[0-9]+/g)];
        let arr8 = [...txt.matchAll(/[\u4e00-\u9fa5]+/g)];
        let arr9 = []; //映射原文
        let pinyinText = "";
        arr8.forEach((item, i) => {
          if (i == 0) {
            arr9 = arr9.concat(arr7.slice(0, item.index));
          } else {
            arr9 = arr9.concat(
              arr7.slice(arr8[i - 1].index + arr8[i - 1][0].length, item.index)
            );
          }
          arr9 = arr9.concat(
            replaceUnicode(pinyin(item[0], { type: "array" }))
          );
        });
        if (arr8.length > 0)
          arr9 = arr9.concat(
            arr7.slice(arr8.at(-1).index + arr8.at(-1)[0].length)
          );

        const simpleVowelsDict = [
          "ā",
          "á",
          "ǎ",
          "à",
          "ō",
          "ó",
          "ǒ",
          "ò",
          "ē",
          "é",
          "ě",
          "è",
          "ī",
          "í",
          "ǐ",
          "ì",
          "ū",
          "ú",
          "ǔ",
          "ù",
          "ǖ",
          "ǘ",
          "ǚ",
          "ǜ",
          "ü",
          "ɑ",
          "ń",
          "ň",
        ];

        let length = 0; //记录每次换行前的拼音行的数组长度
        arr9.forEach((pinyinItem, pinyinIndex) => {
          if (pinyinItem == "\n") {
            let gap = 0;
            arr7
              .slice(pinyinIndex - length, pinyinIndex)
              .forEach((item, index) => {
                let char = arr7[pinyinIndex - length + index];
                let pin = arr9[pinyinIndex - length + index];
                if (gap % 8 == 0 && !/[0-9]|，|。|”|）|\n|\r/.test(char)) {
                  pinyinText += item.padEnd(pin.length) + " ";
                } else pinyinText += item.padEnd(pin.length);
                if (/[\u4e00-\u9fff]+/g.test(char)) {
                  gap += 1;
                }
              });
            length = 0;
          } else {
            pinyinText += pinyinItem + " ";
            length++;
          }
        });
        pObj.addText(pinyinText);
        let out = fs.createWriteStream(
          filePaths +
            "\\" +
            file.name.replace(path.extname(file.name), "") +
            ".docx"
        );
        docx.generate(out);
        out.on("error", (err) => {
          errFiles.push(file.name);
          if (err.message.includes("resource busy or locked")) {
            return alert(
              "生成Word错误：" +
                "请先关闭相同目录下的同名文件 " +
                path.basename(err.message)
            );
          } else {
            return alert("生成Word错误：" + err.message);
          }
        });
        out.on("close", () => {
          let obj = {
            progress: processCount,
            total: filec.length,
            errFiles,
          };
          if (processCount == files.length) {
            span = document.querySelector(".progress-span");
            if (span !== null) {
              span.remove();
              span = document.createElement("span");
              span.className = "progress-span";
              span.innerText = "注音完毕，共注音" + processCount + "个文件";
            } else {
              span.innerText = "注音完毕，共注音" + processCount + "个文件";
            }
            document.querySelector(".progress-box").append(span);
            createOpenLink(filePaths);
            ipcRenderer.send("setProgress", obj);

          }
          processCount++;
        });
      });
      break;
    case "ChineseWordMarkPolyphonicPinyin":
      files.forEach((file, index) => {
        docx = null;
        docx = officegen("docx");
        let pObj = docx.createP();
        const txt = fs.readFileSync(file.path, "utf-8");
        // 1.先拿整段注音，以获得准确的拼音
        let arr7 = txt.split("");
        let arr10 = [...txt.matchAll(/[0-9]+/g)];
        let arr8 = [...txt.matchAll(/[\u4e00-\u9fa5]+/g)];
        let arr9 = []; //映射原文
        let pinyinText = "";
        arr8.forEach((item, i) => {
          if (i == 0) {
            arr9 = arr9.concat(arr7.slice(0, item.index));
          } else {
            arr9 = arr9.concat(
              arr7.slice(arr8[i - 1].index + arr8[i - 1][0].length, item.index)
            );
          }
          arr9 = arr9.concat(
            replaceUnicode(pinyin(item[0], { type: "array" }))
          );
        });
        if (arr8.length > 0)
          arr9 = arr9.concat(
            arr7.slice(arr8.at(-1).index + arr8.at(-1)[0].length)
          );

        const simpleVowelsDict = [
          "ā",
          "á",
          "ǎ",
          "à",
          "ō",
          "ó",
          "ǒ",
          "ò",
          "ē",
          "é",
          "ě",
          "è",
          "ī",
          "í",
          "ǐ",
          "ì",
          "ū",
          "ú",
          "ǔ",
          "ù",
          "ǖ",
          "ǘ",
          "ǚ",
          "ǜ",
          "ü",
          "ɑ",
          "ń",
          "ň",
        ];

        let length = 0; //记录每次换行前的拼音行的数组长度
        arr9.forEach((pinyinItem, pinyinIndex) => {
          if (pinyinItem == "\n") {
            let gap = 0;
            arr7
              .slice(pinyinIndex - length, pinyinIndex)
              .forEach((item, index) => {
                let char = arr7[pinyinIndex - length + index];
                let pin = arr9[pinyinIndex - length + index];
                if (gap % 7 == 0 && !/[0-9]|，|。|”|）|\n|\r/.test(char)) {
                  if (
                    pinyin(item, { multiple: true, type: "array" }).length > 1
                  ) {
                    pObj.addText(item.padEnd(pin.length), {
                      color: "ff0000",
                      bold: true,
                    });
                    pObj.addText(" ");
                  } else {
                    pObj.addText(item.padEnd(pin.length));
                    pObj.addText(" ");
                  }
                } else {
                  if (
                    pinyin(item, { multiple: true, type: "array" }).length > 1
                  ) {
                    pObj.addText(item.padEnd(pin.length), {
                      color: "ff0000",
                      bold: true,
                    });
                  } else {
                    pObj.addText(item.padEnd(pin.length));
                  }
                }
                if (/[\u4e00-\u9fff]+/g.test(char)) {
                  gap += 1;
                }
              });
            length = 0;
          } else {
            if (
              pinyinItem
                .split("")
                .findIndex((item) => simpleVowelsDict.includes(item)) !== -1 ||
              /[a-zA-Z]/.test(pinyinItem)
            ) {
              if (
                pinyin(arr7[pinyinIndex], { multiple: true, type: "array" })
                  .length > 1
              ) {
                pObj.addText(pinyinItem, { color: "ff0000", bold: true });
                pObj.addText(" ");
              } else {
                pObj.addText(pinyinItem);
                pObj.addText(" ");
              }
            } else {
              if (
                pinyin(arr7[pinyinIndex], { multiple: true, type: "array" })
                  .length > 1
              ) {
                pObj.addText(pinyinItem, { color: "ff0000", bold: true });
                pObj.addText(" ");
              } else {
                pObj.addText(pinyinItem);
                pObj.addText(" ");
              }
            }
            length++;
          }
        });

        let out = fs.createWriteStream(
          filePaths +
            "\\" +
            file.name.replace(path.extname(file.name), "") +
            ".docx"
        );
        docx.generate(out);
        out.on("error", (err) => {
          errFiles.push(file.name);
          if (err.message.includes("resource busy or locked")) {
            return alert(
              "生成Word错误：" +
                "请先关闭相同目录下的同名文件 " +
                path.basename(err.message)
            );
          } else {
            return alert("生成Word错误：" + err.message);
          }
        });
        out.on("close", () => {
          let obj = {
            progress: processCount,
            total: filec.length,
            errFiles,
          };
          if (processCount == files.length) {
            span = document.querySelector(".progress-span");
            if (span !== null) {
              span.remove();
              span = document.createElement("span");
              span.className = "progress-span";
              span.innerText = "注音完毕，共注音" + processCount + "个文件";
            } else {
              span.innerText = "注音完毕，共注音" + processCount + "个文件";
            }
            document.querySelector(".progress-box").append(span);
            createOpenLink(filePaths);
            ipcRenderer.send("setProgress", obj);

          }
          processCount++;
        });
        //每次生成完一个就反馈给主进程，同时反馈给页面


      });
      break;
    default:
      break;
  }
}

let getStringPinyin = (txt) => {
  let arr7 = txt.split("");
  let arr8 = [...txt.matchAll(/[\u4e00-\u9fa5]+/g)];
  let pinyinText = "";
  arr8.forEach((item, i) => {
    if (i == 0) {
      pinyinText += arr7.slice(0, item.index).join("");
    } else {
      pinyinText += arr7
        .slice(arr8[i - 1].index + arr8[i - 1][0].length, item.index)
        .join("");
    }
    pinyinText += replaceUnicode(pinyin(item[0]));
  });
  if (arr8.length > 0)
    pinyinText += arr7
      .slice(arr8.at(-1).index + arr8.at(-1)[0].length)
      .join("");
  return pinyinText;
};

let replaceUnicode = (tar) => {
  let isReplace = false; //可由用户选择设置
  if (isReplace) {
    if (tar instanceof Array) {
      return tar.map((p) => p.replaceAll("a", "α"));
    } else {
      return tar.replaceAll("a", "α");
    }
  } else {
    return tar;
  }
};

ipcRenderer.on("done", (ev, data) => {
  if (!readDirerr && data.errFiles.length == 0) alert("已完成");
  if (data.errFiles.length !== 0) alert("出错文件：", data.fileNames.join(","));
});

//用户选择文件夹
function readDir() {
  return dialog.showOpenDialog({
    title: "选择保存拼音的文件夹",
    buttonLabel: "选择",
    properties: ["openDirectory"],
  });
}
module.exports = {
  handlePinyin,
  replaceUnicode,
};
